package com.example.capstome;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class DB_Manager_Adapter extends RecyclerView.Adapter<DB_Manager_Adapter.ViewHolder> {
    private Context context;
    private DB_Helper dbHelper;

    public DB_Manager_Adapter(Context context) {
        this.context = context;
        this.dbHelper = new DB_Helper(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.db_manager_table, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        SQLiteDatabase db = dbHelper.getReadableDatabase(); // 获取数据库实例
        String query = "SELECT name AS table_name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'";
        Cursor cursor = db.rawQuery(query, null); // 执行查询
        if (cursor.moveToPosition(position)) {
            String tableName = cursor.getString(0);
            holder.tableName.setText(tableName); // 获取表名
            DB_Manager_Table_Adapter adapter = new DB_Manager_Table_Adapter(context, tableName);
            LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
            holder.table.setLayoutManager(layoutManager);
            holder.table.setAdapter(adapter);
        }
        cursor.close(); // 关闭Cursor释放资源
    }

    @Override
    public int getItemCount() {
        String query_table = "SELECT COUNT(*) AS table_count FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'";
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery(query_table, null);
        if (cursor.moveToFirst()){
            int table_num = cursor.getInt(0);
            db.close();
            return table_num;
        }
        else {
            //错误信息
            return 1;
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tableName;
        RecyclerView table;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tableName = itemView.findViewById(R.id.tv_TableName);
            table = itemView.findViewById(R.id.rv_Table);
        }
    }
}